<?php

namespace app\admin\controller\meet;

use app\admin\model\meet\OrderImages;
use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['relatedImage','delImage'];

    /**
     * Order模型对象
     * @var \app\admin\model\meet\Order
     */
    protected $model = null;

    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\meet\Order;
        $this->view->assign("genderList", $this->model->getGenderList());
        $this->view->assign("payStatusList", $this->model->getPayStatusList());
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        //实付金额
        $pay_amount = $this->model->where($where)->where(['pay_status' => $this->model::PAY_STATUS_PAYED, 'order_status' => ['gt', $this->model::ORDER_STATUS_CANCEL]])->sum('pay_price');

        //已退还押金
        $refund_deposit = $this->model->where($where)->where(['pay_status' => $this->model::PAY_STATUS_PAYED, 'order_status' => ['gt', $this->model::ORDER_STATUS_CANCEL], 'is_refund_deposit' => $this->model::IS_REFUND_DEPOSIT_YES])->sum('refund_money');

        $result = ['total' => $list->total(), 'rows' => $list->items(), 'extend' => ['pay_amount' => (float)$pay_amount, 'refund_deposit' => (float)$refund_deposit]];
        return json($result);
    }

    public function detail($ids)
    {
        $row = $this->model->get($ids, ['products', 'user']);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    public function cancel($ids)
    {
        $orderLogic = new \app\common\logic\meet\Order();

        $result = $orderLogic->cancelOrder($ids);

        if (!$result) {
            $this->error($orderLogic->getError());
        }

        //删除定时取消任务
        (new \app\common\model\meet\Cron())->where(['event' => 'CronMeetOrderCancel', 'relate_id' => $ids])->delete();

        $this->success();
    }

    public function complete($ids)
    {
        $orderLogic = new \app\common\logic\meet\Order();

        $result = $orderLogic->completeOrder($ids);

        if (!$result) {
            $this->error($orderLogic->getError());
        }

        //删除订单完成任务
//        (new \app\common\model\meet\Cron())->where(['event' => 'CronMeetOrderComplete', 'relate_id' => $ids])->delete();

        $this->success();
    }

    public function progress($ids)
    {
        $orderLogic = new \app\common\logic\meet\Order();

        $result = $orderLogic->progressOrder($ids);

        if (!$result) {
            $this->error($orderLogic->getError());
        }

        $this->success();
    }

    public function refunddeposit($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $orderLogic = new \app\common\logic\meet\Order();

        $result = $orderLogic->refundDeposit($row);

        if (!$result) {
            $this->error($orderLogic->getError());
        }

        $this->success();
    }

    public function modifytime($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function image()
    {
        $order_id = $this->request->param('order_id/d', 0);

        $this->model = new OrderImages();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $this->view->assign('order_id', $order_id);
            return $this->view->fetch();
        }

        $condition = [
            'order_id' => $order_id
        ];


        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $list = $this->model
            ->where($where)
            ->where($condition)
            ->order($sort, $order)
            ->paginate($limit);

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function relatedImage()
    {
        $order_id = $this->request->param('order_id/d', 0);
        $image = $this->request->param('image/s', '');

        if (empty($order_id) || empty($image)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $model = new OrderImages();

        $model->save([
            'order_id' => $order_id,
            'user_id' => $this->model->where('id', '=', $order_id)->value('user_id'),
            'image' => $image
        ]);

        $this->success();
    }

    public function delImage($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        $this->model = new OrderImages();

        $pk = $this->model->getPk();

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
